package socks;

import java.io.BufferedInputStream;


import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.util.Log;


public class InputStreamWrapper extends FilterInputStream {
	private int count = 0;//读取到第几个字节
	
	public InputStreamWrapper(InputStream in) {
		super(in);
	}
	
	/**
	 * 第一位是后续头部的个数-6个
	 */
	private void readHead() throws IOException {
		int r = super.read();
		if(r >= 0 && r <= 255 ) {
			count ++;
		} else {
			return;
		}
		int headCount =  r - 6;
		if( headCount > 0 ) {
			for( int i =0; i < headCount; i++ ) {
				super.read();
				if(r >= 0 && r <= 255 ) {
					count ++;
				} else {
					return;
				}
			}
		}
		Log.i(InputStreamWrapper.class.getName(),"InputStreamWrapper read head headcount:" + headCount);
	}
	
	public int read() throws IOException {
		if( count == 0 ) {
			readHead();
		}
		
		int r = super.read();
		int er = EncodeUtil.decode( r ,count);
		Log.d(InputStreamWrapper.class.getName(),"InputStreamWrapper 4:" + r + "=>" + er + ";count=" + count );
		if(r >= 0 && r <= 255 ) {
			count ++;
		}
		return er;
	}
	
    public int read(byte[] b, int offset, int length) throws IOException {
    	if( count == 0 ) {
			readHead();
		}
    	
    	int len = super.read( b,  offset,  length);
    	EncodeUtil.decode(b, offset, length, count);
    	Log.d(InputStreamWrapper.class.getName(),"InputStreamWrapper read:len=" + len + ";count="+ count + ":" + new String(b,offset,  length) );
    	if( len > 0 ) {
    		count = count + len;
    	}
    	return len;
    }
    
    public int read(byte[] buffer) throws IOException {
        return read(buffer, 0, buffer.length);
    }
    
    public static byte norByte(byte b ) {

    	return (byte)(~ b);
	}

}
